

<template>
  <!-- 积分商品提交订单页面 -->
  <view class="Mall4j container">
    <view class="submit-order">
      <!-- 收货地址 -->
      <view class="delivery-addr" @tap="toAddrListPage">
        <view v-if="!userAddr" class="addr-bg">
          <view class="add-addr">
            <view class="plus-sign-img">
              <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/plus-sign.png" />
            </view>
            <text>{{ i18n.addNewAddress }}</text>
          </view>
          <view class="arrow empty" />
        </view>
        <view v-if="userAddr" class="addr-bg whole">
          <view class="addr-icon">
            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/addr.png" />
          </view>
          <view class="user-info">
            <text class="item">{{ userAddr.receiver }}</text>
            <text class="item">{{ userAddr.mobile }}</text>
          </view>
          <view class="addr">{{ userAddr.province }}{{ userAddr.city }}{{ userAddr.area }}{{ userAddr.addr }}</view>
          <view class="arrow" />
        </view>
      </view>
      <!-- 店铺商品明细 -->
      <view class="prod-item">
        <view class="item-box">
          <!-- 商品信息 -->
          <view class="item-cont">
            <view class="prod-pic">
              <image v-if="productItemDto.pic" :src="productItemDto.pic" />
              <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png" mode="aspectFit" />
            </view>
            <view class="prod-info">
              <view class="prodname">{{ productItemDto.prodName }}</view>
              <view class="prod-info-cont">{{ productItemDto.skuName }}</view>
              <view class="show-price">
                <view class="price-nums">
                  <text class="prodprice"><text v-if="productItemDto.price" class="symbol">￥</text>
                    <text v-if="productItemDto.price" class="big-num">{{ wxs.parsePrice(productItemDto.price)[0] }}</text>
                    <text v-if="productItemDto.price" class="small-num">.{{ wxs.parsePrice(productItemDto.price)[1] }}</text>
                    <text v-if="productItemDto.price" class="small-num" decode="true">&ensp;+&ensp;</text>
                    <text class="big-num">{{ (productItemDto.scorePrice / productItemDto.prodCount) }} {{ i18n.integral }}</text>
                  </text>
                  <text class="prodcount">x{{ productItemDto.prodCount }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- /店铺商品明细 -->
      <!-- 店铺优惠券和买家留言 -->
      <view class="order-msg">
        <view class="msg-item">
          <view class="item">
            <text>{{ i18n.storeNotes }}：</text>
            <input v-model="remarks" maxlength="100" :placeholder="i18n.storeNotesTips"></input>
          </view>
        </view>

      </view>
      <!-- /店铺优惠券和买家留言 -->
      <!-- 总金额计算 -->
      <view class="order-msg">
        <view class="msg-item">
          <!-- 商品总额 -->
          <view class="item">
            <view class="item-tit">{{ i18n.comTotal }}：</view>
            <view class="item-txt price">
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(total)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(total)[1] }}</text>
            </view>
          </view>
          <!-- 运费 -->
          <view class="item">
            <view class="item-tit">{{ i18n.shipping }}：</view>
            <view class="item-txt price">
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(transfee)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(transfee)[1] }}</text>
            </view>
          </view>
          <!-- 平台开启会员包邮(运费减免) -->
          <view v-if="freeTransfee" class="item">
            <view class="item-tit">{{ i18n.memberPackage }}：</view>
            <view class="price item-txt">
              <text class="symbol">-￥</text>
              <text class="big-num">{{ wxs.parsePrice(freeTransfee)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(freeTransfee)[1] }}</text>
            </view>
          </view>
          <!-- 优惠金额 -->
          <view v-if="orderReduce" class="item">
            <view class="item-tit">{{ i18n.preferentialAmount }}：</view>
            <view class="item-txt price">
              <text class="symbol">-￥</text>
              <text class="big-num">{{ wxs.parsePrice(orderReduce)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(orderReduce)[1] }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- /总金额计算 -->
    </view>

    <!-- 底部栏 -->
    <view class="submit-order-footer">
      <view class="sub-order">
        <view class="item-txt">{{ i18n.total }}:<view class="price">
            <text v-if="actualTotal" class="symbol">￥</text>
            <text v-if="actualTotal" class="big-num">{{ wxs.parsePrice(actualTotal)[0] }}</text>
            <text v-if="actualTotal" class="small-num">.{{ wxs.parsePrice(actualTotal)[1] }}</text>
            <text v-if="actualTotal" class="small-num" decode="true">&ensp;+&ensp;</text>
            <text class="big-num">{{ scorePrice }} {{ i18n.integral }}</text>
          </view>
        </view>
      </view>
      <view class="footer-box" @tap="toPay">{{ i18n.submitOrders }}</view>
    </view>
  </view>
</template>

<script module="wxs" lang="wxs" src="../../../wxs/number.wxs"></script>

<script>
// pages/submit-order/submit-order.js
var http = require("@/utils/http.js");
var big = require("@/utils/big.min.js");
import coupon from "@/components/coupon/index.vue";

export default {
  data () {
    return {
      popupShow: false,
      couponSts: 1,
      couponList: [],
      // 订单入口 0购物车 1立即购买
      orderEntry: "0",
      userAddr: null,
      orderItems: [],
      shopCartOrders: [],
      //所有店铺的数据
      productItemDto: [],
      //商品信息
      coupons: {
        totalLength: 0,
        canUseCoupons: [],
        noCanUseCoupons: []
      },
      actualTotal: 0,
      total: 0,
      totalCount: 0,
      transfee: 0,
      freeTransfee: 0,
      reduceAmount: 0,
      couponIds: [],
      orderReduce: 0,
      platformCoupons: [],
      //整个订单可以使用的优惠券列表
      scorePrice: 0,
      remarks: '',
      //留言
      isPurePoints: false // 是否纯积分商品

    };
  },

  components: {
    coupon
  },
  props: {},

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderEntry: options.orderEntry
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 设置头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.submitOrders
    });
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];

    if (currPage.selAddress == "yes") {
      this.setData({
        //将携带的参数赋值
        userAddr: currPage.item
      });
    } //获取订单数据

    this.loadOrderData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
  methods: {
    //加载订单数据
    loadOrderData: function () {
      var addrId = 0;
      if (this.userAddr != null) {
        addrId = this.userAddr.addrId;
      }
      var params = {
        url: "/p/score/confirm",
        method: "POST",
        data: {
          addrId: addrId,
          orderItem: this.orderEntry === "1" ? JSON.parse(wx.getStorageSync("orderItem")) : undefined,
          basketIds: this.orderEntry === "0" ? JSON.parse(wx.getStorageSync("basketIds")) : undefined,
          couponIds: this.couponIds,
          userChangeCoupon: 1
        },
        callBack: res => {
          var shopCartOrders = res.shopCartOrders;
          // 运费
          // let transfee = Number(new big(res.totalTransfee).minus(new big(res.freeTransfee)).valueOf())
          this.setData({
            // shopCartOrders: shopCartOrders, //每个店铺的购物车信息
            productItemDto: res.productItemDto,
            //商品信息
            actualTotal: res.actualTotal,
            //实际总值
            total: res.total,
            //商品总值
            totalCount: res.totalCount,
            //商品总数
            userAddr: res.userAddr,
            //地址Dto
            scorePrice: res.productItemDto.scorePrice, //商品所需积分
            // 运费
            // transfee: transfee >= 0 ? transfee : 0,
            transfee: res.totalTransfee,
            // 用户等级免运费金额
            freeTransfee: res.freeTransfee
          });
        },
        errCallBack: res => {
          this.chooseCouponErrHandle(res);
        }
      };
      http.request(params);
    },

    /**
     * 优惠券选择出错处理方法
     */
    // chooseCouponErrHandle(res) {
    //   // 优惠券不能共用处理方法
    //   if (res.statusCode == 601) {
    //     uni.showToast({
    //       title: res.data,
    //       icon: "none",
    //       duration: 3000,
    //       success: res => {
    //         this.setData({
    //           couponIds: []
    //         })
    //       }
    //     })
    //     setTimeout(() => {
    //       this.loadOrderData();
    //     }, 2500)
    //   }
    // },

    /**
     * 提交订单
     */
    toPay: function () {
      if (!this.userAddr) {
        uni.showToast({
          title: this.i18n.pleaseSelectSddress,
          icon: "none"
        });
        return;
      }

      this.submitOrder();
    },
    // 提交订单
    submitOrder: function () {
      var params = {
        url: "/p/score/submit",
        method: "POST",
        data: {
          remarks: this.remarks
        },
        callBack: res => {
          var isPurePoints = -1
          this.actualTotal == 0 ? isPurePoints = 1 : isPurePoints = -1
          uni.navigateTo({
            url: '/pages/pay-way/pay-way?orderNumbers=' + res.orderNumbers + '&isPurePoints=' + isPurePoints
          });
        }
      };
      http.request(params);
    },

    /**
     * 唤起微信支付
     */
    calWeixinPay: function (orderNumbers) {
      if (this.actualTotal == 0) {
        this.setData({
          isPurePoints: true
        });
      }
      var params = {
        url: "/p/order/pay",
        method: "POST",
        data: {
          payType: 1,
          orderNumbers: orderNumbers
        },
        callBack: res => {
          if (this.isPurePoints) {
            uni.navigateTo({
              url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.orderType
            });
          } else {
            wx.requestPayment({
              timeStamp: res.timeStamp,
              nonceStr: res.nonceStr,
              package: res.packageValue,
              signType: res.signType,
              paySign: res.paySign,
              success: e => {
                uni.navigateTo({
                  url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.orderType
                });
              },
              fail: err => {
                uni.navigateTo({
                  url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.orderType
                });
              }
            });
          }
        }
      };
      http.request(params);
    },
    changeCouponSts: function (e) {
      this.setData({
        couponSts: e.currentTarget.dataset.sts
      });
    },
    // 店铺优惠券弹框
    showCouponPopup: function (e) {
      var index = e.currentTarget.dataset.index;
      var shopCartOrders = this.shopCartOrders;
      this.setData({
        coupons: shopCartOrders[index].showCoupons,
        popupShow: true
      });
    },
    closePopup: function () {
      this.setData({
        popupShow: false
      });
    },

    /**
     * 去地址页面
     */
    toAddrListPage: function () {
      uni.navigateTo({
        url: '/pages/delivery-address/delivery-address?order=0'
      });
    },

    /**
     * 确定选择好的优惠券
     */
    choosedCoupon: function () {
      this.loadOrderData();
      this.setData({
        popupShow: false
      });
    },

    /**-
     * 优惠券子组件发过来
     */
    checkCoupon: function (e) {
      var ths = this;
      let index = ths.couponIds.indexOf(e.detail.couponId);

      if (index === -1) {
        ths.couponIds.push(e.detail.couponId);
      } else {
        ths.couponIds.splice(index, 1);
      }
    },

    /**
     * 输入备注
     */
    onRemarkIpt: function (e) {
      var index = e.currentTarget.dataset.index;
      var shopCartOrders = this.shopCartOrders;
      shopCartOrders[index].remarks = e.detail.value;
      this.setData({
        shopCartOrders: shopCartOrders
      });
      console.log(e.detail.value);
    }
  }
};
</script>
<style>
@import "./integral-submit-order.css";
</style>
